﻿from fastapi import FastAPI, HTTPException
from pydantic import BaseModel, Field
import pymysql
import uvicorn
from datetime import datetime
import json
import os

app = FastAPI(title="视频日志插入API")

# 数据库配置
DB_CONFIG = {
    "host": "localhost",       # 数据库地址
    "user": "root",            # 数据库用户名
    "password": "thisispassword",    # 数据库密码
    "database": "mydb",        # 数据库名
    "charset": "utf8mb4"
}

LOG_DIR = "logs"  # 日志目录


# 确保日志目录存在
os.makedirs(LOG_DIR, exist_ok=True)


# Pydantic模型 (字段和表结构对应)
class Video(BaseModel):
    user_id: str = Field(..., description="用户ID，主键之一，必填")
    vid: str = Field(..., description="视频ID，主键之一，必填")
    title: str | None = None
    category: str | None = None
    author: str | None = None
    publish_time: str | None = None
    duration: int | None = None
    labels: str | None = None
    play_time: str | None = None
    play_duration: int | None = None
    likes: int | None = None
    favourites: int | None = None
    shares: int | None = None


def write_log(video: Video):
    """写日志到按日期命名的文件"""
    today = datetime.now().strftime("%Y-%m-%d")
    log_file = os.path.join(LOG_DIR, f"api_calls_{today}.log")
    log_entry = {
        "time": datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
        "params": video.model_dump()
    }
    with open(log_file, "a", encoding="utf-8") as f:
        f.write(json.dumps(log_entry, ensure_ascii=False) + "\n")


# 插入接口（支持播放时长累加 + 每日日志）
@app.post("/add_video")
def add_video(video: Video):
    try:
        # 写日志
        write_log(video)

        # 插入/更新数据库
        conn = pymysql.connect(**DB_CONFIG)
        cursor = conn.cursor()

        sql = """
        INSERT INTO viewlogs (
            user_id, vid, title, category, author, publish_time,
            duration, labels, play_time, play_duration,
            likes, favourites, shares
        ) VALUES (
            %(user_id)s, %(vid)s, %(title)s, %(category)s, %(author)s, %(publish_time)s,
            %(duration)s, %(labels)s, %(play_time)s, %(play_duration)s,
            %(likes)s, %(favourites)s, %(shares)s
        )
        ON DUPLICATE KEY UPDATE
            play_duration = IFNULL(play_duration, 0) + VALUES(play_duration),
            likes = VALUES(likes),
            favourites = VALUES(favourites),
            shares = VALUES(shares),
            play_time = VALUES(play_time)
        """

        cursor.execute(sql, video.model_dump())
        conn.commit()
        return {"message": "✅ 视频信息插入成功（新数据或已存在数据已更新）"}

    except Exception as e:
        raise HTTPException(status_code=500, detail=f"数据库错误: {e}")

    finally:
        cursor.close()
        conn.close()


# 启动服务
if __name__ == "__main__":
    uvicorn.run("main:app", host="0.0.0.0", port=8001, reload=True)
